import path from 'path';

import { expect } from '@jest/globals';
import fse from 'fs-extra';
import JSON5 from 'json5';

import { initExecuteCommand, runHvigorAsync } from '../../common/common';
import { addOhPackageDps } from '../../plugins/common-fun';
import {
  AbilityType,
  APIType,
  APIVersion,
  CaseLevel,
  LanguageType,
  ModuleTemplateType,
  RuntimeOSType,
  SDKType,
} from '../../plugins/project-builder/models/constants';
import { TestCaseBuilder } from '../../plugins/task-builder/task-case-builder';
import { ProjectBuildOption, TestCaseFun } from '../../plugins/task-builder/test-case';
import { TestTaskOptionBuilder } from '../../plugins/task-builder/test-task-option';

const projectBuilderOption: ProjectBuildOption = {
  template: {
    sdk: SDKType.Single,
    runtimeOS: RuntimeOSType.HarmonyOS,
    apiVersion: APIVersion.API11,
    apiType: APIType.STAGE,
    language: LanguageType.ArkTs,
    abilityType: AbilityType.Application,
    entryTemplateType: ModuleTemplateType.EmptyAbility,
  },
  modulesOption: {
    [ModuleTemplateType.SharedLibrary]: 1
  },
};

const testFun: TestCaseFun = async (project, taskConfig, record) => {
  const projectRootPath = project.projectRootPath();
  // sync
  const syncCommands = initExecuteCommand({
    mode: 'project',
    product: 'default',
    tasks: '--sync',
  });
  const syncResult = await runHvigorAsync(projectRootPath, syncCommands);
  record.addStep('sync', syncResult);
  expect(syncResult.stdout).toContain('Finished ::init...');

  // 给entry增加hsp依赖，
  const entryModulePath = project.getModule('entry').moduleRootPath();
  await addOhPackageDps(entryModulePath, {
    'shareLibrary': 'file:../shareLibrary',
  });

  // 将entry和hsp的build-profile.json5中的obfuscation.ruleOptions.enable置为true
  const entryBuildProfile = await fse.readFile(path.resolve(entryModulePath, 'build-profile.json5'));
  const entryBuildProfileJson = JSON5.parse(entryBuildProfile.toString());
  entryBuildProfileJson.buildOptionSet[0].arkOptions.obfuscation.ruleOptions.enable = true;
  await fse.writeFile(path.resolve(entryModulePath, 'build-profile.json5'), JSON.stringify(entryBuildProfileJson));
  const hspModuleRootPath = project.getModule('shareLibrary').moduleRootPath();
  const hspBuildProfile = await fse.readFile(path.resolve(hspModuleRootPath, 'build-profile.json5'));
  const hspBuildProfileJson = JSON5.parse(hspBuildProfile.toString());
  hspBuildProfileJson.buildOptionSet[0].arkOptions.obfuscation.ruleOptions.enable = true;
  if (hspBuildProfileJson.buildOptionSet[0].arkOptions.obfuscation.consumerFiles === undefined) {
    hspBuildProfileJson.buildOptionSet[0].arkOptions.obfuscation.consumerFiles = ['./consumer-rules.txt'];
  }
  if (!hspBuildProfileJson.buildOptionSet[0].arkOptions.obfuscation.consumerFiles.includes('./consumer-rules.txt')) {
    hspBuildProfileJson.buildOptionSet[0].arkOptions.obfuscation.consumerFiles.push('./consumer-rules.txt');
  }
  const hspConsumerRulesPath = path.resolve(hspModuleRootPath, 'consumer-rules.txt');
  fse.ensureFileSync(hspConsumerRulesPath);
  await fse.writeFile(path.resolve(hspModuleRootPath, 'build-profile.json5'), JSON.stringify(hspBuildProfileJson));

  // 执行全量编译构建命令
  const buildCommand =
    '--mode module -p product=default -p buildMode=release assembleHap --analyze=normal --parallel --incremental --daemon';
  const buildResult = await runHvigorAsync(projectRootPath, buildCommand.split(' '));
  record.addStep('build', buildResult);
  expect(buildResult.stdout).toContain('BUILD SUCCESSFUL');

  // 修改hsp的consumer-rules.txt内容，再全量编译，查看entry:default@CompileArkTS任务是否走了增量
  const hspObfuscationRules = '-keep-global-name\nPerson';
  fse.appendFileSync(hspConsumerRulesPath, hspObfuscationRules);
  const secondBuildResult = await runHvigorAsync(projectRootPath, buildCommand.split(' '));
  record.addStep('secondBuild', secondBuildResult);
  expect(secondBuildResult.stdout).toContain('BUILD SUCCESSFUL');
  expect(secondBuildResult.stdout).toContain('Finished :entry:default@CompileArkTS');
};

// SDK未配套交付, E2E暂时屏蔽
TestCaseBuilder.builder()
  .caseName('DTS2025010722280')
  .description(
    '1 创建stage工程；\n' +
      '2 创建hsp依赖；\n' +
      '3 sync；\n' +
      '4 全量编译构建entry；\n' +
      '5 修改hsp的consumer-rules.txt；\n' +
      '6 编译构建entry，查看entry:default@CompileArkTS任务是否走了增量；'
  )
  .projectBuilderOption(projectBuilderOption)
  .taskConfig(TestTaskOptionBuilder.builder().caseLevel(CaseLevel.AR).build())
  .testFun(testFun)
  .load();
